package com.twxm.breed.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class UploadUtil {
    private static String ProjectPath = null;

    public static String getProjectPath(){
        if(ProjectPath != null){
            return ProjectPath;
        }
        try {
            File directory = new File("");// 参数为空
            ProjectPath = directory.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ProjectPath;
    }

    public static String saveFile(String pathName, MultipartFile file,String pathName2){
        if (file.isEmpty()){
            log.info("文件为空。。。");
            return null;
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("filename:" + fileName);
        // 指定文件保存的目录
        String path = getProjectPath() + "/save/"+pathName+"/"+pathName2+"/";
        File dir = new File(path);
        String savePath = path + fileName;
        if(!dir.exists()){
            dir.mkdirs();
        }
        if (isExistFileName(savePath)){
            fileName = setFileName(fileName);
            savePath = path + fileName;
        }
        if (file.getSize() < 10485760){
            //小于10mb
            return uploadSmallFile(file,savePath);
        }else{
            return null;
        }
    }
    private static String uploadSmallFile(MultipartFile file,String savePath){
        //pathName = user、excel、pond
        try {
            log.info("正在上传:",savePath);
            // 创建输出流，将文件保存到指定目录下
            OutputStream outputStream = new FileOutputStream(savePath);
            // 获取文件的输入流
            InputStream inputStream = file.getInputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
        return savePath;
    }

    private static boolean isExistFileName(String savePath){
        Path path = Paths.get(savePath);
        // 检查文件名是否已经存在
        return !Files.exists(path);
    }

    private static String setFileName(String filename) {
        Path path;
        String oldFileName = filename;
        String extName = getExtName(filename);
        // 如果文件名已经存在，则在文件名后面添加时间戳
        while (true) {
            String newFilename = String.format("%s_%s.", getBaseName(oldFileName), getTimeStamp()) + extName;
            path = Paths.get(newFilename);
            if (!Files.exists(path)) {
                filename = newFilename;
                break;
            }
        }
        return filename;
    }

    private static String getBaseName(String filename) {
        int index = filename.lastIndexOf('.');
        return (index == -1) ? filename : filename.substring(0, index);
    }

    private static String getExtName(String filename) {
        int index = filename.lastIndexOf('.');
        return (index == -1) ? "" : filename.substring(index + 1);
    }



    private static String getTimeStamp() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        return now.format(formatter);
    }

    //大于10mb，切片上传
    private static String uploadMultiFile(MultipartFile file, String savePath,boolean firstChunk,String path,String fileName){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try{
            // 大文件分片上传合并
            // 新建一个文件，这时候内容是空的
            File localFile = new File(savePath);
            boolean append;
            if(firstChunk && localFile.exists()){
                // 第一个chunk， 而且存在了
                // 那就覆盖
                // no append
                append = false;
            }else{
                // append 追加到后面
                append = true;
            }
            File temp = File.createTempFile(path, "temp" + fileName);
            file.transferTo(temp);
            fis = new FileInputStream(temp);
            fos = new FileOutputStream(localFile, append);

            byte[] buf = new byte[1024];
            int len = 0;
            while(-1!=(len=fis.read(buf))){
                fos.write(buf);
            };
            fos.flush();
            fos.close();
            fos = null;
            fis.close();
            fis = null;
            temp.delete();
            return savePath;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try{
                if(fis!=null){
                    fis.close();
                }
                if(fos!=null){
                    fos.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
